﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using seo.Data;
using seo.Buz;
using System.IO;

namespace seo
{
    class BlackHat
    {
        private const int start_page = 3;
        private const int end_page = 50;
        private const int standard_length = 200;

        public string article { get; set; }
        public string title { get; set; }
        public Website website { get; set; }
        public Keyword keyword { get; set; }

        private WebSiteBuz websiteBuz = new WebSiteBuz();
        private KeywordBuz keywordBuz = new KeywordBuz();
        private HttpHelper httpHelper = new HttpHelper();
        private ContentBuz contentBuz = new ContentBuz();

        private static List<string> censor_words_list = null;
        private static string word_cover = null;
        private int max_censor = 2;

        static BlackHat()
        {
            if (censor_words_list != null) return;
            censor_words_list = new List<string>();
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory;
                string[] lines = File.ReadAllLines(path + "\\CensorWords.txt", Encoding.GetEncoding("GB2312"));
                foreach (string line in lines)
                {
                    string[] words = line.Split('=');
                    censor_words_list.Add(words[0]);
                    if (word_cover == null) word_cover = words[1];
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public BlackHat()
        {
        }

        public BlackHat(Website _website, Keyword _keyword)
        {
            website = _website;
            keyword = _keyword;
        }

        public BlackHat(string _article)
            : this(_article, null)
        {
        }

        public BlackHat(string _article, Website _website)
            : this(_article, _website, null)
        {
        }

        public BlackHat(string _article, Website _website, Keyword _keyword)
        {
            article = _article;
            website = _website;
            keyword = _keyword;
        }

        public string FilterArticle(string _text)
        {
            string result = _text;
            foreach (string censor_word in censor_words_list)
            {
                result = result.Replace(censor_word, word_cover);
            }
            if (result.Split(new string[] { word_cover }, StringSplitOptions.None).Length > max_censor + 1) result = String.Empty;
            return result;
        }

        /***
         * 生成软文
         * */
        public void CreateArticle()
        {
            //暂定关键字为英语，下个版本开发使用
            //string keywordToSearch = GoogleTranslate.Translate(keyword.keyword, "zh-CN", "en");

            Random r = new Random((int)DateTime.Now.Ticks);
            int start = r.Next(start_page, end_page) * 10;
            string html = GoogleSearch.Search(keyword.keyword, start);

            List<string> urlList = null;
            HtmlAnalyzer ha = new HtmlAnalyzer();
            urlList = ha.getUrlList(html);

            GetContent getContent = new GetContent();


            if (urlList != null && urlList.Count > 0)
            {
                string url = urlList[r.Next(urlList.Count)];
                html = httpHelper.sendRequest(url);
                title = getContent.getTitle(html).Trim();
                title = GoogleTranslate.Translate(title, "en", "zh-CN");
                title = title.Split('-', '_', '|')[0];
                html = getContent.getContentUsingParser(html);
                article = ha.deleteHtml(html);
            }

            if (article != null && article != "")
            {
                article = GoogleTranslate.Translate(article, "en", "zh-CN");
                //article = RemoveUselessString(article);
            }
        }

        public string RemoveUselessString(string _article)
        {
            string result = _article;
            System.Text.RegularExpressions.Regex regex0 = new System.Text.RegularExpressions.Regex(@"[&#]+[0-9]*?;", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = regex0.Replace(result, String.Empty);
            System.Text.RegularExpressions.Regex regex1 = new System.Text.RegularExpressions.Regex(@"[a-zA-Z#%;％]", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            result = regex1.Replace(result, String.Empty);
            return result;
        }

        /***
         * 随机产生链接数
         * min = 最小链接数
         * max = 最大链接数
         * */
        public int GetRandomUrlCount(int min, int max)
        {
            Random r = new Random((int)DateTime.Now.Ticks);
            int result = r.Next(min, max + 1);
            return result;
        }

        public Website ChooseWebsite(string belong_group)
        {
            Website chosenWebsite = null;
            //获取belong_group组的域名导入值总和
            int total_imp_value = websiteBuz.getTotalImpValue(belong_group);
            //获取belong_group组的域名list
            List<Website> list = websiteBuz.getWebsiteByBelongGroup(belong_group);
            //随机选择域名
            Random r = new Random((int)DateTime.Now.Ticks);
            int choose_value = r.Next(total_imp_value);
            foreach (Website site in list)
            {
                if (choose_value < site.imp_value)
                {
                    chosenWebsite = site;
                    break;
                }
                else
                {
                    choose_value -= site.imp_value;
                }
            }
            return chosenWebsite;
        }

        public Keyword ChooseKeyword(Website site)
        {
            Keyword chosenKeyword = null;
            //获取site的关键词权重总和
            int total_keyword_weight = keywordBuz.getTotalKeywordWeight(site.id);
            //获取site的关键词list
            List<Keyword> list = keywordBuz.getKeywordListBySiteId(site.id);
            //随机选择关键词
            Random r = new Random((int)DateTime.Now.Ticks);
            int choose_value = r.Next(total_keyword_weight);
            foreach (Keyword word in list)
            {
                if (choose_value < word.keyword_weight)
                {
                    chosenKeyword = word;
                    break;
                }
                else
                {
                    choose_value -= word.keyword_weight;
                }
            }
            return chosenKeyword;
        }

        public string ChooseNativePageUrl(Website site, Keyword word)
        {
            string chosenUrl = contentBuz.GetNativeUrlByKeyword(site, word);
            if (chosenUrl == null || chosenUrl.Length == 0) chosenUrl = site.domainname;
            return chosenUrl;
        }

        public string GetTitle()
        {
            // Decide the title of article
            Random r = new Random((int)DateTime.Now.Ticks);
            int title_length = r.Next(5, 16);
            string title = article.Substring(r.Next(article.Length - title_length), title_length);
            int i = 0;
            while (i < title.Length)
            {
                if (Encoding.UTF8.GetByteCount(title.Substring(i, 1)) == 1) title = title.Remove(i, 1); else i++;
            }
            if (title.Trim().Length == 0) title = keyword.keywordchinese;
            return title;
        }

        public void Excute()
        {
            title = String.Empty;
            //生成软文
            CreateArticle();

            if (article == null || article == string.Empty || article.Length < standard_length) return;
            string article_left = article;
            //忽略中文字数少于文章总字数一半的文章 一个中文占3个byte 一个英文占1个byte
            if (Encoding.UTF8.GetByteCount(article_left) < 2 * article_left.Length) return;

            // while (article_left != null && article_left.Length >= standard_length)
            //{                
            // if (article_left.Length < standard_length * 2)
            // {
            //     article = article_left;
            //     article_left = String.Empty;
            // }
            // else
            // {
            //     article = article_left.Substring(0, standard_length);
            //    article_left = article_left.Substring(standard_length);
            // }

            if (article == null || article.Length == 0) return;

            //随机产生链接数
            int urlCount = GetRandomUrlCount(website.minlink, website.maxlink);

            //导出主页百分比

            Random r = new Random((int)DateTime.Now.Ticks);
            int[] positions = new int[urlCount];
            string[] urls = new string[urlCount];
            for (int i = 0; i < urlCount; i++)
            {
                if (r.Next(100) < website.exp_pcnt)
                {
                    //外链
                    //选择网站
                    Website chosenWebsite = ChooseWebsite(website.exp_group);
                    //选择关键词
                    Keyword chosenKeyword = ChooseKeyword(chosenWebsite);

                    string url = String.Empty;
                    if (r.Next(100) < chosenWebsite.imp_home_pcnt)
                    {
                        //主页
                        url = chosenWebsite.domainname;
                    }
                    else
                    {
                        //内页
                        url = ChooseNativePageUrl(chosenWebsite, chosenKeyword);
                    }
                    string html = String.Format(@"<a href='{0}'>{1}</a>", url, chosenKeyword.keywordchinese);
                    //插入链接
                    positions[i] = r.Next(article.Length);
                    urls[i] = html;
                    //article.Insert(r.Next(article.Length), html);
                }
                else
                {
                    //内链
                    string url = website.domainname;
                    string html = String.Format(@"<a href='{0}'>{1}</a>", url, keyword.keywordchinese);
                    //插入链接
                    positions[i] = r.Next(article.Length);
                    urls[i] = html;
                    //article.Insert(r.Next(article.Length), html);
                }
            }
            if (title == String.Empty) title = GetTitle();
            Array.Sort(positions);
            for (int i = positions.Length - 1; i >= 0; i--)
            {
                article = article.Insert(positions[i], urls[i]);
            }
            //插入远程DB
            article = FilterArticle(article);
            if (article.Trim() != string.Empty && article.Length >= standard_length)
            {
                article = article.Replace("\n", "<br>"); // \n在html页面中显示不出来，必须替换成<br>
                contentBuz.insertContent(website, keyword, article, title);
            }
            //  }
        }
    }
}
